﻿using System;
using System.Reflection;
using UnityEngine;
using UnityEditor;
using Framework.Define;

namespace FrameworkEditor.UITools.UIGenerate
{
    public class UIGeneratePrefab : UIGenerateBase
    {
        private string mUIName = string.Empty;
        private string mPrefabFileName = string.Empty;

        private bool mIsSubPanel = false;
        private string mMainPanelName = string.Empty;

        public UIGeneratePrefab(string pUIName, bool pIsSubPanel, string pMainPanelName)
        {
            mUIName = pUIName;
            mPrefabFileName = string.Format("{0}.prefab", pUIName);

            mIsSubPanel = pIsSubPanel;
            if (!mIsSubPanel)
                mMainPanelName = pUIName;
            else
                mMainPanelName = pMainPanelName;
        }

        public void GeneratePrefab()
        {
            string prefabFileFullPath = string.Format("{0}/{1}/{2}/Prefabs/{3}", Application.dataPath, FrameworkDefine.UIRootDirectoryPath, mMainPanelName, mPrefabFileName);

            if (CheckExistFile(prefabFileFullPath, mPrefabFileName))
            {

                string directoryFullPath = string.Format("{0}/{1}/{2}/Prefabs", Application.dataPath, FrameworkDefine.UIRootDirectoryPath, mMainPanelName);
                CreateDirectory(directoryFullPath);

                string prefabFileRelativePath = string.Format("Assets/{0}/{1}/Prefabs/{2}", FrameworkDefine.UIRootDirectoryPath, mMainPanelName, mPrefabFileName);

                GameObject instanceGameObject = CreateInstanceGameObject();
                PrefabUtility.SaveAsPrefabAsset(instanceGameObject, prefabFileRelativePath);
                GameObject.DestroyImmediate(instanceGameObject, true);
            }
        }

        private GameObject CreateInstanceGameObject()
        {
            GameObject instanceGameObject = new GameObject(mPrefabFileName);
            RectTransform rectTransform = instanceGameObject.AddComponent<RectTransform>();
            rectTransform.anchorMin = Vector2.zero;
            rectTransform.anchorMax = Vector2.one;
            rectTransform.offsetMin = Vector2.zero;
            rectTransform.offsetMax = Vector2.zero;

            return instanceGameObject;
        }
    }
}